//
//  MJTOAuthViewController.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/10.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit

import SVProgressHUD
import AFNetworking
//微博Appkey
let WeiboAppKey = "3121524851"
//微博appsecret
let WeiboAppSecret = "7513839f9b94b88bdba2146b29c7ae5a"
//微博授权回调页
let WeiboRedirect_Url = "http://www.baidu.com"
class MJTOAuthViewController: UIViewController {

    //MARK:  -懒加载
    private lazy var webView: UIWebView = UIWebView()
    override func loadView() {
        //自定义视图
        webView.delegate = self
        view = webView

        webView.opaque = false
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.backgroundColor = UIColor.whiteColor()
        //取消 自动调整ScrollView插图
        //        self.automaticallyAdjustsScrollViewInsets = false

        setUpNavUI()
        requestOAuth()

    }
    //请求数据
    private func requestOAuth() {
        //请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Url)"
        let request = NSURLRequest(URL: NSURL(string:url)!)
        //加载请求
        webView.loadRequest(request)
    }
    //modal出webView
    private func setUpNavUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    }
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充字段
    @objc private func autoFillAction() {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '13253643283@163.com';document.getElementById('passwd').focus();document.getElementById('passwd').value = 'taotao123'")
    }
}
extension MJTOAuthViewController:UIWebViewDelegate {
    //将要加载 http://www.baidu.com/?code=88bdb5eedb88c01274c441ac5128ecbb
    //每次发送URL请求的时候都会调用这个方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL else {
            return false
        }
        //获取URL的绝对地址
        if !url.absoluteString.hasPrefix(WeiboRedirect_Url) {
            return true
        }
        if let query = url.query where query.hasPrefix("code=") {
            //截获code
            let code = query.substringFromIndex("code=".endIndex)
//            requestAccesstoken(code)
            MJTUserAccountViewModel.shareUserAccount.requestAccesstoken(code, callBack: { (isSucess) -> () in
                if isSucess {
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //发送通知释放资源
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                } else {
                    print("登录失败")
                }
            })
//            print(code)
        } else {
            // 取消回调
            dismissViewControllerAnimated(true, completion: nil)
        }
        return false
    }
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}